<template>
  <div v-loading="loading" class="padding">
    <div class="search-form">
      <el-form inline>
        <year-month-picker v-model="time"></year-month-picker>
        <el-form-item>
          <el-button icon="el-icon-search" type="primary" @click="clickSearch">
            查询
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <regional-chart
      v-if="chartData"
      title="区域能源消费统计"
      :data="chartData"
    ></regional-chart>
    <regional-table
      ref="table"
      class="margin-top"
      :energy-type-options="energyType"
      :data="tableData"
      @change="handleChangeCheckbox"
      @loadMore="loadMore"
    ></regional-table>
  </div>
</template>

<script>
import YearMonthPicker, {
  getTimeTypeFromTime
} from '@/components/year-month-picker';
import RegionalChart from './chart';
import RegionalTable from './table';

import MixinChart from './mixin-chart';
import MixinTable from './mixin-table';
import { uuid } from '@/utils';

export default {
  name: 'regional-data-presentation',
  mixins: [MixinChart, MixinTable],
  components: {
    RegionalChart,
    RegionalTable,
    YearMonthPicker
  },
  data() {
    return {
      loading: false,
      time: ''
    };
  },
  computed: {
    timeType() {
      return getTimeTypeFromTime(this.time);
    }
  },
  mounted() {
    this.$store
      .dispatch('getEnergyType')
      .then(() => {
        this.getAllData();
      })
      .catch(e => {
        console.warn(e);
      });
  },
  methods: {
    getParams() {
      const tableRef = this.$refs.table;
      return {
        time: this.time,
        timeType: this.timeType,
        energyTypeList: tableRef ? tableRef.checked.join(',') : ''
      };
    },
    async getAllData() {
      this.loading = true;
      await this.getChartData();
      await this.getTableData();
      this.loading = false;
    },
    clickSearch() {
      this.getAllData();
    },
    loadMore(tree, treeNode, resolve) {
      this.loadTableMore(tree, treeNode)
        .then(res => {
          const keys = ['enterpriseCode', 'enterpriseId', 'enterpriseName'];
          (res.data.tbody || []).forEach(item => {
            Object.keys(item).forEach(key => {
              if (!keys.includes(key)) {
                item[key] = item[key] || '-';
              }
            })
          });
          resolve(
            (res.data.tbody || []).map(item => ({
              ...item,
              // 将企业名称显示出来
              districtName: item.enterpriseName,
              uuid: uuid()
            }))
          );
        })
        .catch(e => {
          console.warn(e);
          resolve([]);
        });
    }
  }
};
</script>
